<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Googleapi{
	
	function __construct() {
		$this->ci =& get_instance();
		$this->ci->load->config('stareit', TRUE);
		//$this->ci->load->library('session');
	}
	
    function lookupFeed($query_url) {
        
        $url = "https://ajax.googleapis.com/ajax/services/feed/lookup?"."v=1.0&q=".urlencode($query_url);    
		$url = $this->addRequiredParams($url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        $body = curl_exec($ch);
        curl_close($ch);
    
        
        $json = json_decode($body);
        
        return $json;
    }

	
	function getTopSearchKeywords(){
		$url = "http://www.google.com/m/services/trends/get?hl=zh-TW&gl=tw&category=web&nocache=".time();
		$url = $this->addRequiredParams($url);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		
		$result = curl_exec($ch);
		//echo "<pre>";print_r($result);echo "</pre>";
		curl_close($ch);
		$doc = new DOMDocument();
				
		$doc->strictErrorChecking = FALSE;		
		$doc->loadXML($result);
		$xml = simplexml_import_dom($doc);
		
		//echo "<pre>";print_r($xml);echo "</pre>";
		return $xml->item;
	}
	
    function getBlogResults($start='',$q) {
        $google_blog_search = 'http://ajax.googleapis.com/ajax/services/search/blogs?hl=zh-TW&ie=UTF-8&v=1.0&rsz=large';
		
		$google_blog_search = $this->addRequiredParams($google_blog_search);
		
        if ($start=='') {
            
            $start = '0';
            $url = $google_blog_search."&q=".urlencode($q)."&start=".$start;
			//echo $url;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $body = curl_exec($ch);
            curl_close($ch);
            $json = json_decode($body);
        } else {
            $url = $google_blog_search."&q=".urlencode($q)."&start=".$start;
			
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $body = curl_exec($ch);
            curl_close($ch);
            $json = json_decode($body);
        }
		
    	return $json;
    }
	
	private function addRequiredParams($url){
		$google_api_key = $this->ci->config->item('google_api_key', 'stareit');
		
		$USER_IP_ADDR = $_SERVER['REMOTE_ADDR'];
        $url .= '&key='.$google_api_key.'&userip='.$USER_IP_ADDR;
		
		return $url;
	}
	
}


?>